import React, { useState } from 'react';
import { useParams, useNavigate } from 'react-router-dom';
import { Space, Button, Avatar, Form, Input, List, Tag, Card, message, Modal, Typography } from 'antd';
import { UserOutlined, EditOutlined, DeleteOutlined, LikeOutlined, LikeFilled, MessageOutlined } from '@ant-design/icons';
import ReactMarkdown from 'react-markdown';
import { useUser } from '../../contexts/UserContext';
import './ArticleDetail.scss';

const { TextArea } = Input;
const { confirm } = Modal;
const { Paragraph } = Typography;

interface IArticle {
    id: string;
    title: string;
    content: string;
    author: {
        id: string;
        username: string;
        avatar?: string;
    };
    createdAt: string;
    updatedAt: string;
    likes: number;
    comments: number;
    tags: string[];
}

interface IComment {
    id: string;
    content: string;
    author: {
        id: string;
        username: string;
        avatar?: string;
    };
    articleId: string;
    createdAt: string;
    updatedAt: string;
}

const ArticleDetail: React.FC = () => {
    const { id } = useParams<{ id: string }>();
    const navigate = useNavigate();
    const { user } = useUser();
    const [submitting, setSubmitting] = useState(false);
    const [commentValue, setCommentValue] = useState('');
    const [isLiked, setIsLiked] = useState(false);
    const [likesCount, setLikesCount] = useState(42);
    const [comments, setComments] = useState<IComment[]>([
        {
            id: '1',
            content: '写得很好，对我帮助很大！',
            author: {
                id: '2',
                username: 'user1',
                avatar: 'https://joeschmoe.io/api/v1/random'
            },
            articleId: '1',
            createdAt: new Date().toISOString(),
            updatedAt: new Date().toISOString()
        }
    ]);

    // 示例数据
    const mockArticle: IArticle = {
        id: '1',
        title: "React Hooks 最佳实践",
        content: `
# React Hooks 最佳实践

## 为什么使用 Hooks？

Hooks 是 React 16.8 中新增的特性。它可以让你在不编写 class 的情况下使用 state 以及其他的 React 特性。

### 主要优势

- 更容易复用状态逻辑
- 将相关联的逻辑放在一起
- 避免 class 组件的 this 问题

\`\`\`javascript
import React, { useState, useEffect } from 'react';

function Example() {
    const [count, setCount] = useState(0);

    useEffect(() => {
        document.title = \`You clicked \${count} times\`;
    });

    return (
        <div>
            <p>You clicked {count} times</p>
            <button onClick={() => setCount(count + 1)}>
                Click me
            </button>
        </div>
    );
}
\`\`\`

## 常见的 Hooks

1. useState
2. useEffect
3. useContext
4. useReducer
5. useCallback
6. useMemo
7. useRef

> 注意：Hooks 只能在函数组件的顶层使用

| Hook | 用途 |
|------|------|
| useState | 状态管理 |
| useEffect | 副作用处理 |
| useContext | 上下文管理 |
| useReducer | 复杂状态管理 |

![React Hooks Flow](https://reactjs.org/docs/hooks-overview.html)
`,
        author: {
            id: '1',
            username: '张三'
        },
        createdAt: new Date().toISOString(),
        updatedAt: new Date().toISOString(),
        likes: likesCount,
        comments: comments.length,
        tags: ["React", "Hooks", "JavaScript", "前端开发"]
    };

    const handleLike = () => {
        if (!user) {
            message.warning('请先登录后再点赞！');
            return;
        }

        setIsLiked(!isLiked);
        setLikesCount(prev => isLiked ? prev - 1 : prev + 1);
        // TODO: 调用API更新点赞状态
    };

    const handleSubmitComment = () => {
        if (!user) {
            message.warning('请先登录后再评论！');
            return;
        }

        if (!commentValue.trim()) {
            message.warning('评论内容不能为空！');
            return;
        }

        setSubmitting(true);
        // 模拟API调用
        setTimeout(() => {
            const newComment: IComment = {
                id: String(Date.now()),
                content: commentValue,
                author: {
                    id: user.id,
                    username: user.username,
                    avatar: user.avatar
                },
                articleId: mockArticle.id,
                createdAt: new Date().toISOString(),
                updatedAt: new Date().toISOString()
            };

            setComments(prev => [newComment, ...prev]);
            setCommentValue('');
            setSubmitting(false);
            message.success('评论发布成功！');
        }, 1000);
    };

    const handleDelete = () => {
        confirm({
            title: '确认删除',
            content: '确定要删除这篇文章吗？删除后将无法恢复。',
            okText: '确定',
            okType: 'danger',
            cancelText: '取消',
            onOk() {
                // TODO: 调用API删除文章
                message.success('文章删除成功！');
                navigate('/articles');
            }
        });
    };

    return (
        <div className="article-detail">
            <Card 
                title={mockArticle.title}
                extra={
                    user?.id === mockArticle.author.id && (
                        <Space>
                            <Button 
                                type="primary" 
                                icon={<EditOutlined />}
                                onClick={() => navigate(`/articles/edit/${id}`)}
                            >
                                编辑
                            </Button>
                            <Button 
                                danger 
                                icon={<DeleteOutlined />}
                                onClick={handleDelete}
                            >
                                删除
                            </Button>
                        </Space>
                    )
                }
            >
                <div className="article-meta">
                    <div>
                        <Avatar icon={<UserOutlined />} /> {mockArticle.author.username}
                        <span style={{ margin: '0 16px' }}>{new Date(mockArticle.createdAt).toLocaleDateString()}</span>
                        {mockArticle.tags.map(tag => (
                            <Tag key={tag} color="blue">{tag}</Tag>
                        ))}
                    </div>
                    <div className="article-actions">
                        <Button 
                            type="text" 
                            icon={isLiked ? <LikeFilled /> : <LikeOutlined />}
                            onClick={handleLike}
                            className={isLiked ? 'liked' : ''}
                        >
                            {likesCount}
                        </Button>
                        <Button 
                            type="text" 
                            icon={<MessageOutlined />}
                            onClick={() => {
                                const commentInput = document.querySelector('.comment-input');
                                if (commentInput) {
                                    commentInput.scrollIntoView({ behavior: 'smooth' });
                                }
                            }}
                        >
                            {comments.length}
                        </Button>
                    </div>
                </div>
                <div className="markdown-content">
                    <ReactMarkdown>{mockArticle.content}</ReactMarkdown>
                </div>
                <div className="comments-section">
                    <h3>评论 ({comments.length})</h3>
                    {user ? (
                        <Form style={{ marginBottom: 24 }} className="comment-input">
                            <Form.Item>
                                <TextArea
                                    rows={4}
                                    value={commentValue}
                                    onChange={e => setCommentValue(e.target.value)}
                                    placeholder="说点什么..."
                                />
                            </Form.Item>
                            <Form.Item>
                                <Button
                                    htmlType="submit"
                                    loading={submitting}
                                    onClick={handleSubmitComment}
                                    type="primary"
                                >
                                    发表评论
                                </Button>
                            </Form.Item>
                        </Form>
                    ) : (
                        <Paragraph type="secondary">请登录后发表评论</Paragraph>
                    )}
                    <List
                        dataSource={comments}
                        itemLayout="horizontal"
                        renderItem={comment => (
                            <div className="comment-item">
                                <Avatar src={comment.author.avatar} icon={<UserOutlined />} />
                                <div className="comment-content">
                                    <div className="comment-author">{comment.author.username}</div>
                                    <div className="comment-time">{new Date(comment.createdAt).toLocaleString()}</div>
                                    <div className="comment-text">{comment.content}</div>
                                </div>
                            </div>
                        )}
                    />
                </div>
            </Card>
        </div>
    );
};

export default ArticleDetail; 